Απλά προγράμματα

Clear[fact]

fact[n_]:=Module[{i=0,r=1},
If[n==0,1,
                 While[i!=n,i++;r=r*i]];
r]

Table[fact[k],{k,10}]

fact1[n_]:=Module[{r},
r=1;
If[n==0,1,
                 Do[r=r*i,{i,n}]];
r]

Table[fact1[k],{k,10}]

fact2[n_]:=Module[{r},
r=1;
If[n==0,Return[1],
                 Do[r=r*i,{i,n}]];
Return[r]]

Table[fact2[k],{k,10}]

fib[n_]:=Module[{f0=0,f1=1,f2},
Do[f2=f0+f1;
     f0=f1;
     f1=f2,{n}];
f0]

{Fibonacci[21],fib[21]}

TableForm[Table[{k,Fibonacci[k],fib[k],Factorial[k],fact[k]},{k,10}],
    TableHeadings->{None,{"k","Fibonacci","fib","Factorial","fact"}}]

reverse[v_]:=Module[{rv,len=Length[v]},
rv=Table[0,{len}];
Do[rv[[i]]=v[[len-i+1]], {i,1,len}];
rv]

v=RandomInteger[100,15];
rv=reverse[v];
 rv

transpose[mat_]:=Module[{trmat, r=Dimensions[mat][[1]],c=Dimensions[mat][[2]]},
trmat=Table[0,{c},{r}];
Do[trmat[[i,j]]=mat[[j,i]],
     {i,1,c},{j,1,r}];
trmat]

mat={{a,b,c},{d,e,f} (*,{g,h,k} *) }
trmat=transpose[mat]

Dimensions[mat]

mat//MatrixForm
trmat//MatrixForm

i1=RandomInteger[{1,10}]
j1=RandomInteger[{1,10}]
mat=RandomInteger[15,{i1,j1}]
trmat=transpose[mat]
mat//MatrixForm
trmat//MatrixForm

permute[s_,p_]:=Module[{t=Table[0,{Length[s]}],temp},
Do[temp=p[[i]];
t[[temp]]=s[[i]],
     {i,Length[s]}];
t]

permute[{"a","b","c","d"},{3,1,4,2}]

sieve[n_]:=Module[{count,result=Range[n],i, primes={}},
result[[1]]=0;i=2;
While[i^2≤n,
           If[result[[i]]≠0,For[j=2*i,j≤n,j+=i,result[[j]]=0]];
           i++];
count=0;
For[k=1,k≤n,k++,If[result[[k]]>0,AppendTo[primes, result[[k]]]; count++]];
Print["There are ", count, " primes less than ", n,  " and these are: "];
Print[ primes]]

sieve[20]